﻿using System;
using System.Collections;
using Google.GData.Photos;

namespace TruyenTranhCrawler.Helper
{
    public class GoogleHelper
    {
        public static AlbumAccessor GetAvailableAlbum(PicasaService service, string username)
        {
            var query = new AlbumQuery(PicasaQuery.CreatePicasaUri(username));

            PicasaFeed feed = service.Query(query);

            foreach (PicasaEntry entry in feed.Entries)
            {
                AlbumAccessor ac = new AlbumAccessor(entry);
                if (ac.NumPhotos < ac.NumPhotosRemaining)
                    return ac;
            }
            //create new album for this
            var album = new AlbumEntry { Title = { Text = DateTime.Now.ToString() } };
            var aac = new AlbumAccessor(album) { Access = "public" };

            var feedUri = new Uri(PicasaQuery.CreatePicasaUri(username));
            var albumEntry = service.Insert(feedUri, album);
            return new AlbumAccessor(albumEntry);
        }
        public static SortedList UploadImageToGoogle(string path, string fileName, string username, string password, string appName="appname")
        {
            if (!System.IO.File.Exists(path))
                return new SortedList();

            var service = new PicasaService(appName);
            service.setUserCredentials(username, password);

            var fileInfo = new System.IO.FileInfo(path);
            var fileStream = fileInfo.OpenRead();

            var albumId = GetAvailableAlbum(service, username).Id;
            var postUri = new Uri(PicasaQuery.CreatePicasaUri(username, albumId));
            var entry = (PicasaEntry)service.Insert(postUri, fileStream, "image/png", fileName);
            fileStream.Close();
            return entry.Media.Content.Attributes;
        }

        /// <summary>
        /// Get blogger account from config: 
        /// <add key="googleaccounts" value="nick@gmail.com,password"/>
        /// </summary>
        /// <returns></returns>
        public static GoogleBloggerAccount GetBloggerAccount(string keyName = "googleaccounts")
        {
            var list = System.Configuration.ConfigurationManager.AppSettings[keyName].Split(',');
            var acc = new GoogleBloggerAccount { UserName = list[0], Password = list[1]};
            return acc;
        }
    }

    public class GoogleBloggerAccount
    {
        public string UserName { get; set; }
        public string Password { get; set; }
    }
}
